package com.sqlist.share.resolver.impl;

import android.os.Message;
import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.sqlist.share.MainActivity;
import com.sqlist.share.connection.Client;
import com.sqlist.share.dto.LinkDTO;
import com.sqlist.share.dto.MessageDTO;
import com.sqlist.share.resolver.DataResolver;
import com.sqlist.share.util.GsonUtils;

import java.lang.reflect.Type;

import io.netty.channel.Channel;

/**
 * Created by SqList on 2018/6/13.
 */

public class LinkDTODataResolver implements DataResolver {
    private static final String TAG = "Share - LinkDTODataResolver";
    @Override
    public void resolve(String messageString, Channel channel) {
        Log.i(TAG, "resolver()" + messageString);

        // 含有泛型的具体类别 装换为 具体类别
        Type type = new TypeToken<MessageDTO<LinkDTO>>(){}.getType();
        MessageDTO<LinkDTO> messageDTO = GsonUtils.getInstance().fromJson(messageString, type);

        Message message = new Message();

        if (messageDTO.getData().getStatus() == LinkDTO.LINK_FAIL) {
            Log.i(TAG, "连接失败， " + messageDTO.getMsg());
            message.what = LinkDTO.LINK_FAIL;

            Log.i(TAG, "停止netty长连接");
            Client.getInstance().disConnect();
        } else {
            Log.i(TAG, messageDTO.getMsg());
            message.what = LinkDTO.LINK_SUCCESS;
        }

        Log.i(TAG, "给 MainActivity 传递 Handler");
        if (MainActivity.getHandler() != null) {
            MainActivity.getHandler().sendMessage(message);
        }
    }
}
